package com.gph.saviorframework.security.web.controller;

import com.github.pagehelper.PageHelper;
import com.gph.saviorframework.Constants;
import com.gph.saviorframework.ErrorCode;
import com.gph.saviorframework.SaviorFrameworkException;
import com.gph.saviorframework.common.model.Function;
import com.gph.saviorframework.common.model.Module;
import com.gph.saviorframework.security.service.FunctionService;
import com.gph.saviorframework.security.service.ModuleService;
import com.gph.saviorframework.security.web.editor.ModuleEditor;
import com.gph.saviorframework.util.RequestUtil;
import com.gph.saviorframework.util.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by iscas-qd on 2016/3/5.
 */
@Controller
@RequestMapping("/"+ Constants.FRAMEWORK_REQUEST_PATH + "/function")
public class FunctionController {

    /** 日志输出 */
    final Logger logger = LoggerFactory.getLogger(FunctionController.class);

    /** 领域对象名称 */
    private static final String domain = Function.class.getSimpleName().toLowerCase();

    /** 视图前缀 */
    private final String viewPrefix = Constants.FRAMEWORK_REQUEST_PATH + "/" + Constants.MODULE_CATEGORY_SECURITY + "/" + domain + "/" + domain + "_";

    /** 服务 */
    @Autowired
    private FunctionService functionService;

    @Autowired
    private ModuleService moduleService;

    /** 国际化资源 */
    @Autowired
    private MessageSourceAccessor messages;

    @Autowired
    private SecurityUtils securityUtils;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Module.class, new ModuleEditor(moduleService));
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createPage() throws SaviorFrameworkException {
        return viewPrefix + "create";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap save(@ModelAttribute Function function) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            securityUtils.setCreateEntity(function);
            function.setVersion(0);
            functionService.save(function);
            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
            modelMap.addAttribute(Constants.DEFAULT_ID_KEY, function.getId());
            logger.info(messages.getMessage("log.info.create", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain), function.getId() }));
        }
        catch (DataIntegrityViolationException e) {
            e.printStackTrace();
            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(Constants.DEFAULT_ERROR_KEY, ErrorCode.DATA_INTEGRITY_VIOLATION + "[" + messages.getMessage("menu.error.duplicate.identity") + "]");
            logger.error(messages.getMessage("log.error.create", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain) }));
        }
        catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(Constants.DEFAULT_ERROR_KEY, e.getMessage());
            logger.error(messages.getMessage("log.error.create", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain) }));
        }
        return modelMap;
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String list() throws SaviorFrameworkException {
        return viewPrefix + "index";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public String list(
            @RequestParam(value = Constants.DEFAULT_PAGE_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_START) Integer start,
            @RequestParam(value = Constants.DEFAULT_RECORD_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_PAGE_SIZE) Integer limit,
            @RequestParam(value = Constants.DEFAULT_SORT_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_SORT_FIELD) String sort,
            @RequestParam(value = Constants.DEFAULT_DIR_MODEL_KEY, required = false, defaultValue = Constants.DEFAULT_SORT_DIRECTION) String dir,
            HttpServletRequest request) throws SaviorFrameworkException {
        String json = null;
        Map<String, Object> params = RequestUtil.getQueryMap(request, functionService.getFields());
        try {
            json = com.alibaba.fastjson.JSONArray.toJSONString(functionService.find(start,limit,sort,dir,params));
            logger.info(messages.getMessage("log.info.list", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain) }));
        }
        catch (DataAccessException e) {
            e.printStackTrace();
            logger.error(messages.getMessage("log.error.list", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain) }));
        }
        return json;
    }

    /**
     * 返回编辑页面
     *
     * @return 编辑页面视图名称
     * @throws SaviorFrameworkException
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String editPage() throws SaviorFrameworkException {
        return viewPrefix + "edit";
    }

    /**
     * 更新编辑数据
     *
     * @param id
     * @param request
     * @return
     * @throws SaviorFrameworkException
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
    public @ResponseBody
    ModelMap edit(@PathVariable("id") String id, HttpServletRequest request) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            Function function = functionService.get(id);
            ServletRequestDataBinder binder = new ServletRequestDataBinder(function);
            binder.registerCustomEditor(Module.class, new ModuleEditor(moduleService));
            binder.bind(request);
            securityUtils.setModifyEntity(function);
            function.setVersion(function.getVersion() + 1);
            functionService.update(function);
            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
            logger.info(messages.getMessage("log.info.edit", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain), id}));
        }
        catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(Constants.DEFAULT_ERROR_KEY, ErrorCode.UNCAUGHT_EXCEPTION);
            logger.error(messages.getMessage("log.error.edit", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain), id }));
        }

        return modelMap;
    }

    /**
     * 返回查看页面
     *
     * @return 查看页面视图名称
     * @throws SaviorFrameworkException
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view() throws SaviorFrameworkException {
        return viewPrefix + "view";
    }

    /**
     * 根据ID查询.
     *
     * @param id 主键
     * @return
     */
    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public @ResponseBody
    ModelMap view(@PathVariable("id") String id) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            modelMap.addAttribute("success", Boolean.TRUE);
            modelMap.addAttribute(Constants.DEFAULT_RECORD_MODEL_KEY, functionService.findById(id));
        } catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute("success", Boolean.FALSE);
            modelMap.addAttribute("error", ErrorCode.UNCAUGHT_EXCEPTION);
        }
        return modelMap;
    }

    /**
     * 批量删除.
     * @param ids 主键数组
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public @ResponseBody
    ModelMap delete(@RequestParam(value = "ids", required = true) String[] ids) throws SaviorFrameworkException {
        ModelMap modelMap = new ModelMap();
        try {
            functionService.deleteByIds(ids);
            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY, Boolean.TRUE);
            logger.info(messages.getMessage("log.info.delete", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain),
                    StringUtils.arrayToDelimitedString((Object[]) ids, "|")}));
        }
        catch (DataIntegrityViolationException e) {
            e.printStackTrace();
            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(Constants.DEFAULT_ERROR_KEY, ErrorCode.DATA_INTEGRITY_VIOLATION);
            logger.error(messages.getMessage("log.error.delete", new String[] { securityUtils.getUserFullName(), messages.getMessage(domain),
                    StringUtils.arrayToDelimitedString((Object[]) ids, "|") }));
        }
        catch (Exception e) {
            e.printStackTrace();
            modelMap.addAttribute(Constants.DEFAULT_SUCCESS_KEY, Boolean.FALSE);
            modelMap.addAttribute(Constants.DEFAULT_ERROR_KEY, ErrorCode.UNCAUGHT_EXCEPTION);
            logger.error(messages.getMessage("log.error.delete", new String[]{securityUtils.getUserFullName(), messages.getMessage(domain),
                    StringUtils.arrayToDelimitedString((Object[]) ids, "|")}));
        }
        return modelMap;
    }
}
